import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
import { HttpService } from 'http-service';
import { API } from "../../../shared/models/api-path-extension";

@Injectable()
export class CardService {
  public cardAddOrDelStatus$: Observable<object>;
  public cardReorderStatus$: Observable<Array<any>>;
  private cardAddOrDelStatusSource = new Subject<object>();
  private cardReorderStatusSource = new Subject<Array<any>>();
  
  private api: API;
  constructor(
    public httpService: HttpService
  ) {
    this.api = new API();
    this.cardAddOrDelStatus$ = this.cardAddOrDelStatusSource.asObservable();
    this.cardReorderStatus$ = this.cardReorderStatusSource.asObservable();
  }

  changeStatus(card: object) {
    this.cardAddOrDelStatusSource.next(card);
  }

  reorderCard(cards: Array<any>) {
    this.cardReorderStatusSource.next(cards);
  }

  saveUserCards(userId, userCardList): Promise<any> {
    let cards = userCardList.map((card, index) => {
      let _c = {
        isAvailable: card.isAvailable,
        userId: userId,
        cardId: card.id,
        sequence: index
      };
      if (card.cardUserId) {
        _c['cardUserId'] = card.cardUserId;
      }
      return _c;
    });
    return this.httpService.post(this.api.path({ path: "cardListByUser" }).baseURL, cards).toPromise();
  }
}
